'use strict';
const Service = require('egg').Service;
const { Op, fn, col } = require('sequelize');

class Finance extends Service {
  /* 增 */
  // 添加收入记录
  async addIncome(body) {
    const { ctx } = this;
    try {
      const income = await ctx.model.Finance.Income.create({
        ...body,
      });
      return income;
    } catch (error) {
      ctx.throw('创建失败');
    }
  }
  async addExpense(body) {
    const { ctx } = this;
    try {
      const expense = await ctx.model.Finance.Expense.create({
        ...body,
      });
      return expense;
    } catch (error) {
      ctx.throw('创建失败');
    }
  }
  /* 删 */
  /* 改 */
  // 收入审核
  async examineIncome({ id, ...info }) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Finance.Income.update(
        {
          ...info,
        },
        {
          where: {
            id,
          },
        }
      );
      if (result[0] > 0) {
        return '审核通过';
      }
      return '审核失败';
    } catch (error) {
      ctx.throw(error);
    }
  }
  // 支出审核
  async examineExpense({ id, ...info }) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Finance.Expense.update(
        {
          ...info,
        },
        {
          where: {
            id,
          },
        }
      );
      if (result[0] > 0) {
        return '审核通过';
      }
      return '审核失败';
    } catch (error) {
      ctx.throw(error);
    }
  }
  // 收入支出审查
  /* 查 */
  // 待审核收入列表
  async findNewIncomeList() {
    const { ctx } = this;
    const List = await ctx.model.Finance.Income.findAll({
      where: {
        state: 0,
      },
      include: [
        {
          model: ctx.model.Contract.Contract,
        },
      ],
    });
    return List;
  }
  async findIncomeListByState({ state }) {
    const { ctx } = this;
    const List = await ctx.model.Finance.Income.findAll({
      where: {
        state,
      },
      include: [
        {
          model: ctx.model.Contract.Contract,
        },
      ],
    });
    return List;
  }
  // 完成审核收入列表
  async FindExaminedIncomeList() {
    const { ctx } = this;
    const List = await ctx.model.Finance.Income.findAll({
      where: {
        state: {
          [Op.ne]: 0,
        },
      },
      include: [
        {
          model: ctx.model.Contract.Contract,
        },
      ],
    });
    return List;
  }
  // 待审核支出列表
  async findNewExpenseList() {
    const { ctx } = this;
    const List = await ctx.model.Finance.Expense.findAll({
      where: {
        state: 0,
      },
      include: [
        {
          model: ctx.model.Sys.User,
        },
      ],
    });
    return List;
  }
  // 完成审核收入列表
  async findExamineExpenseList() {
    const { ctx } = this;
    const List = await ctx.model.Finance.Expense.findAll({
      where: {
        state: {
          [Op.ne]: 0,
        },
      },
      include: [
        {
          model: ctx.model.Sys.User,
        },
      ],
    });
    return List;
  }
}
module.exports = Finance;
